//
//  WebViewController.m
//  Youpin
//
//  Created by xiaowuxiaowu on 2017/4/13.
//  Copyright © 2017年 xiaowuxiaowu. All rights reserved.
//

#import "WebViewController.h"
#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import "YYPhotoGroupView.h"
#import "NSString+UrlEncode.h"
@interface WebViewController()<WKUIDelegate,WKNavigationDelegate,UIWebViewDelegate>{
}


@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) NSUInteger loadCount;
@property (nonatomic, copy)NSArray *imgArray;

//判断是否是HTTPS的
@property (nonatomic, assign) BOOL isAuthed;

//返回按钮
@property (nonatomic, strong) UIBarButtonItem *backItem;
//关闭按钮
@property (nonatomic, strong) UIBarButtonItem *closeItem;

@end

@implementation WebViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    if (self.urlstr) {
        
        if([self.urlstr hasPrefix:@"http"]){
            
        }else{
            NSString * urlHead = @"http://";
            self.urlstr = [urlHead stringByAppendingString:self.urlstr];
        }
        
    }
    DLog(@"url = %@",self.urlstr);
    
//#if  __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_8_0
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 自定义配置，一般用于js调用oc方法（oc拦截URL中的数据做自定义操作）
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addUserScript:wkUserScript];
    
    
    //进行配置控制器
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferences = [WKPreferences new];
    configuration.userContentController = userContentController;
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 0.0;
    preferences.javaScriptEnabled = YES;
    configuration.preferences = preferences;
    
  
    self.webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    //    self.webView = [[UIWebView alloc]init];
    //    self.webView.delegate = self;

    if(self.html){
        [self.webView loadHTMLString:self.html baseURL:nil];
    }else
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlstr]]];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(IOS7_TOP_Y);
        make.left.right.bottom.mas_equalTo(0.0f);
    }];
    
    
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectZero];
    self.progressView.trackTintColor = [UIColor clearColor];
    self.progressView.hidden = YES;
    [self.webView addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0.0f);
        make.height.mas_equalTo(2.0f);
    }];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    //
    
    UIImageView *line = [[UIImageView alloc]initWithImage:[UIImage imageWithColor:tableViewSeparatorColor]];
    [self.webView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0.0f);
        make.height.mas_equalTo(0.5f);
    }];
    
    self.leftBtn.hidden = YES;
    [self addLeftButton];
    
}
#pragma mark - 添加关闭按钮

- (void)addLeftButton
{
    self.navigationItem.leftBarButtonItem = self.backItem;
}

//点击返回的方法
- (void)backNative
{
    //判断是否有上一层H5页面
    if ([self.webView canGoBack]) {
        //如果有则返回
        [self.webView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
        [self closeNative];
    }
}

//关闭H5页面，直接回到原生页面
- (void)closeNative
{
    [self leftBtnAction:nil];
}

#pragma mark - init

- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //这是一张“<”的图片，可以让美工给切一张
        UIImage *image = [UIImage imageNamed:@"Nav_left_arrow_black"];
        [btn setImage:image forState:UIControlStateNormal];
        [btn setTitle:@"返回" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //字体的多少为btn的大小
        [btn sizeToFit];
        //左对齐
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //让返回按钮内容继续向左边偏移15，如果不设置的话，就会发现返回按钮离屏幕的左边的距离有点儿大，不美观
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0);
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
        btn.frame = CGRectMake(0, 0, 55, 40);
        _backItem.customView = btn;
    }
    return _backItem;
}

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
        _closeItem.tintColor = [UIColor blackColor];
    }
    return _closeItem;
}


-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    // self.loadCount ++;
    DLog(@"---didStartProvisionalNavigation--");
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //    [self getImageUrlByJS:webView];
    
    DLog(@"---didFinishNavigation--");
    
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id Result, NSError * _Nullable error) {
        DLog(@"----error----%@--%@",error,Result);
        if(Result&&webView.canGoBack){
            self.title = Result;
        }
    }];
    
    NSString *js = @"\
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = '98%';   \
    } \
    ";
    
    [webView evaluateJavaScript:js completionHandler:^(id Result, NSError * _Nullable error) {
        DLog(@"----error----%@--%@",error,Result);
    }];
    
    
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

// 内容返回时
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    //  self.loadCount --;
}
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    self.loadCount --;
    DLog(@"---didFailNavigation--");
}
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    DLog(@"didFailProvisionalNavigation--");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    [self showBigImage:navigationAction.request];
    
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    
    //    if ([keyPath isEqualToString:@"loading"]) {
    //
    //    } else if ([keyPath isEqualToString:@"title"]) {
    //        self.title = self.webView.title;
    //    } else if ([keyPath isEqualToString:@"URL"]) {
    //
    //    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
    //
    //        self.progressView.progress = self.webView.estimatedProgress;
    //    }
    
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
    
}
- (void)setLoadCount:(NSUInteger)loadCount {
    _loadCount = loadCount;
    
    if (loadCount == 0) {
        self.progressView.hidden = YES;
        [self.progressView setProgress:0 animated:NO];
    }else {
        self.progressView.hidden = NO;
        CGFloat oldP = self.progressView.progress;
        CGFloat newP = (1.0 - oldP) / (loadCount + 1) + oldP;
        if (newP > 0.95) {
            newP = 0.95;
        }
        [self.progressView setProgress:newP animated:YES];
        
    }
}
- (NSArray *)getImageUrlByJS:(WKWebView *)wkWebView {
    
    // js方法遍历图片添加点击事件返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgUrlStr='';\
    for(var i=0;i<objs.length;i++){\
    if(i==0){\
    if(objs[i].alt==''){\
    imgUrlStr=objs[i].src;\
    }\
    }else{\
    if(objs[i].alt==''){\
    imgUrlStr+='#'+objs[i].src;\
    }\
    }\
    objs[i].onclick=function(){\
    if(this.alt==''){\
    document.location=\"myweb:imageClick:\"+this.src;\
    }\
    };\
    };\
    return imgUrlStr;\
    };";
    
    // 这里只是将代码添加到web？？？
    [wkWebView evaluateJavaScript:jsGetImages completionHandler:^(id Result, NSError * error) {
        //        NSLog(@"js___Result==%@",Result);
        //        NSLog(@"js___Error -> %@", error);
    }];
    
    // 这里执行？？？
    NSString *js2=@"getImages()";
    
    __block NSArray *array=[NSArray array];
    [wkWebView evaluateJavaScript:js2 completionHandler:^(id Result, NSError * error) {
        DLog(@"js2__Result==%@",Result);
        NSString *resurlt=[NSString stringWithFormat:@"%@",Result];
        
        if([resurlt hasPrefix:@"#"])
        {
            resurlt=[resurlt substringFromIndex:1];
        }
        array=[resurlt componentsSeparatedByString:@"#"];
        DLog(@"array====%@",array);
        _imgArray = array;
    }];
    
    
    return array;
}
//显示大图
-(BOOL)showBigImage:(NSURLRequest *)request
{
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"])
    {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        NSLog(@"image url------%@", imageUrl);
        
        NSArray *imgUrlArr=self.imgArray;
        NSMutableArray *urlArray = [NSMutableArray new];
        
        
        NSInteger index=0;
        for (NSInteger i=0; i<[imgUrlArr count]; i++) {
            
            YYPhotoGroupItem *item = [[YYPhotoGroupItem alloc]init];
            item.largeImageURL = urlNamed(imgUrlArr[i]);
            item.largeImageSize = CGSizeMake(IPHONE_WIDTH, 100);
            if([imageUrl isEqualToString:imgUrlArr[i]])
            {
                index=i;
                item.thumbView = _webView;
            }
            
            [urlArray addObject:item];
        }
        
        
        YYPhotoGroupView *photoGroupView = [[YYPhotoGroupView alloc]initWithGroupItems:urlArray];
        photoGroupView.frame = [UIScreen mainScreen].bounds;
        [photoGroupView presentFromImageView:_webView toContainer:[XWCommon shareAppDelegate].window.rootViewController.view animated:YES completion:nil];
        
        
        //[WFImageUtil showImgWithImageURLArray:[NSMutableArrayarrayWithArray:imgUrlArr] index:index myDelegate:nil];
        
        return NO;
    }
    return YES;
}
-(void)leftBtnAction:(UIButton *)sender{
    if(self.navigationController.viewControllers.count > 1){
        [super leftBtnAction:sender];
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)dealloc{
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end


@interface NSURLRequest (InvalidSSLCertificate)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end
